package service

import (
	"errors"
	"gorm.io/gorm"
	"shop-bean/dto"
	"shop-bean/model"
	"shop-common/library/loggerV2"
	"shop-common/library/variables"
	"shop-common/utils/queryWrapper"
	"shop-service/repository"
)

// todo 还需要梳理这个service接口
type IUserAddrService interface {
	Count(userId string) (int64, error)
	Create(row *model.UserAddr) error
	FindByUserId(addrId uint, userId string) (*dto.UserAddrDTO, error)
	Updates(addrId uint, entity *model.UserAddr) error
	Find(pair *queryWrapper.WherePair) ([]*dto.UserAddrDTO, error)
	UpdateDefaultUserAddr(userId string, addrId uint) error
}

type UserAddrService struct {
	db         *gorm.DB
	repository repository.IUserAddrRepository
}

func NewUserAddrService(repository repository.IUserAddrRepository) IUserAddrService {
	return &UserAddrService{variables.GormDB(), repository}
}

func (s *UserAddrService) Count(userId string) (int64, error) {
	count, err := s.repository.Count(s.db, userId)
	if err != nil {
		loggerV2.Error(err)
		return 0, err
	}
	return count, nil
}

func (s *UserAddrService) Create(row *model.UserAddr) error {
	if err := s.repository.Create(s.db, row); err != nil {
		loggerV2.Error(err)
		return err
	}
	return nil
}

func (s *UserAddrService) FindByUserId(addrId uint, userId string) (entity *dto.UserAddrDTO, err error) {
	if addrId == 0 {
		entity, err = s.repository.FindOneDefaultUserAddr(s.db, userId)
	} else {
		entity, err = s.repository.FindOneUserAddrByUserIdAndAddrId(s.db, userId, addrId)
	}

	if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
		loggerV2.Error(err)
		return nil, err
	}

	return entity, nil
}

func (s *UserAddrService) Updates(addrId uint, entity *model.UserAddr) error {
	if err := s.repository.Updates(s.db, addrId, entity); err != nil {
		//variables.ErrLogger.Sugar().Error("UserAddrService.Updates err : %v", err)
		return err
	}
	return nil
}

func (s *UserAddrService) Find(pair *queryWrapper.WherePair) ([]*dto.UserAddrDTO, error) {
	entity, err := s.repository.Find(s.db, pair)
	if err != nil {
		loggerV2.Error(err)
		return nil, err
	}
	return entity, nil
}

func (s *UserAddrService) UpdateDefaultUserAddr(userId string, addrId uint) error {
	err := s.repository.RemoveDefaultUserAddr(s.db, userId)
	if err != nil {
		loggerV2.Error(err)
		return errors.New("无法修改用户默认地址，请稍后再试")
	}

	err = s.repository.SetDefaultUserAddr(s.db, addrId, userId)
	if err != nil {
		loggerV2.Error(err)
		return errors.New("无法修改用户默认地址，请稍后再试")
	}
	return nil
}

//func FindPage(ctx context.Context, userId string) (*pagehelper.Record, error) {
//	return nil, nil
//}
